﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;

using ClientConclusionListGenerator.FileProcessors;
using OfficeOpenXml;
using OfficeOpenXml.Style;

namespace ClientConclusionListGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Working...");

            IEnumerable<string> files = new string[0];
            Array.ForEach(AppConfig.SrcFolders,
                        (folder) =>
                        {
                            files = files.Concat(Directory.GetFiles(folder, AppConfig.FilePattern, SearchOption.AllDirectories));
                        });

            List<ClientData> clientList = new List<ClientData>();

            for (int i = 0; i < files.Count(); i++)
            {
                Console.Write("\r>>>working on {0}/{1}", (i + 1), files.Count());

                var f = files.ElementAt(i);

                if (AppConfig.ExcludeFileNames.Any(exclude => f.EndsWith(exclude)))
                    continue;

                var info = new FileInfo(f);

                if (info.LastWriteTime < AppConfig.ModifiedTimeAfter)
                    continue;

                var client = ProcessClient(f);

                if (client != null)
                    clientList.Add(client);
            }

            SaveClientData(clientList);

            Console.WriteLine("\nDone!!!");
            Console.ReadLine();
        }

        private static ClientData ProcessClient(string f)
        {
            ClientDataFileV2Processor processor = new ClientDataFileV2Processor();
            if (processor.IsSupport(f))
            {
                return processor.Process(f);
            }
            else
            {
                SimpleLogger.Log(new string[] { "不受支持的文件各式：" + f });
                return null;
            }
        }

        private static void SaveClientData(List<ClientData> clientList)
        {
            if (clientList == null || clientList.Count == 0)
            {
                Console.WriteLine("no data to save!!!");
                return;
            }

            //int totalCount = clientList.Count;
            //clientList = clientList.Where(c => c.MaterialUnpaid > 0).ToList();
            //int saveCount = clientList.Count;

            //Console.WriteLine("未保存的统计表的客户数：" + (totalCount - saveCount));

            string targetFile = Path.Combine(AppConfig.TargetFolder, string.Format("client_conclusion_{0}.xlsx", DateTime.Now.ToString("yyMMddHHmmssfff")));

            // backup old file
            if (File.Exists(targetFile))
            {
                int insertIdx = targetFile.LastIndexOf('.');
                string insertText = "_bak_" + DateTime.Now.ToString("yyMMddHHmmssfff");
                string newFile = targetFile.Insert(insertIdx, insertText);
                File.Move(targetFile, newFile);
            }

            using (var package = new ExcelPackage(new FileInfo(targetFile)))
            {
                var book = package.Workbook;
                var sheet = book.Worksheets.Add("Conclusion");
                sheet.HeaderFooter.OddHeader.CenteredText = "客户欠款概况表";

                sheet.HeaderFooter.OddHeader.LeftAlignedText = Environment.NewLine + "generated at: " + DateTime.Today.ToString("yyyy/m/d");

                #region Set Header Row

                //sheet.View.FreezePanes(1, 1); // may cause file corruption

                // create header cells
                var nameHeaderCell = sheet.Cells[1, 1];
                var materialUnpaidHeaderCell = sheet.Cells[1, 2];
                var phoneHeaderCell = sheet.Cells[1, 3];
                var personHeaderCell = sheet.Cells[1, 4];
                var lastbuydateHeaderCell = sheet.Cells[1, 5];

                // set header cells value
                nameHeaderCell.Value = "姓名";
                materialUnpaidHeaderCell.Value = "欠款";
                phoneHeaderCell.Value = "联系方式";
                personHeaderCell.Value = "联系人";
                lastbuydateHeaderCell.Value = "最后交易日期";


                #endregion

                int skipRowCount = 0; // use for avoiding blank rows

                for (int rowIdx = 0; rowIdx < clientList.Count; rowIdx++)
                {
                    var client = clientList[rowIdx];

                    if (client.MaterialUnpaid < 1 && client.MaterialUnpaid > -1)
                    {
                        skipRowCount++;
                        continue;
                    }

                    #region Set Data Row

                    var curRow = rowIdx - skipRowCount + 2;

                    // column A
                    var nameCell = sheet.Cells[curRow, 1];                    
                    nameCell.Value = client.Name;

                    // column B
                    var materialUnpaidCell = sheet.Cells[curRow, 2];
                    materialUnpaidCell.Style.Numberformat.Format = "0.00#";
                    materialUnpaidCell.Value = client.MaterialUnpaid;

                    // column C
                    var phoneCell = sheet.Cells[curRow, 3];
                    phoneCell.Value = client.Phone;

                    // column D
                    var personCell = sheet.Cells[curRow, 4];
                    personCell.Value = client.ContactPerson;

                    // column E
                    if (client.LastTradeDate.HasValue)
                    {
                        var lastbuydateCell = sheet.Cells[curRow, 5];
                        lastbuydateCell.Value = client.LastTradeDate.Value;
                        lastbuydateCell.Style.Numberformat.Format = "yyyy/m/d";
                    }

                    #endregion
                }


                package.Save();
            }
        }
    }
}